package com.stadyhelper.interceptors;

import com.stadyhelper.Utils.JwtUtil;
import com.stadyhelper.Utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//redis操作类
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //重写preHandle方法，对请求进入到Controller进行拦截
        String token = request.getHeader("Authorization");//从请求头获取JWT令牌
        try {
            //从redis中获取相同的token
            ValueOperations<String,String> ops=stringRedisTemplate.opsForValue();
            String redisToken = ops.get(token);
            if(redisToken==null){
                //redis失效了
                throw new RuntimeException();
            }
            Map<String,Object> claims= JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
